<?php


namespace app\service;


use app\entity\AddressEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqAddAddress;
use app\models\request\ReqId;
use app\models\response\RespAddressDetail;
use app\models\response\RespPage;
use yii\data\Pagination;

class AddressService
{

    /**
     * @param $id
     * @param $userId
     * @return array|\yii\db\ActiveRecord |AddressEntity
     * @throws OaException
     */
    public function findByIdAndUserId($id,$userId) {
        $entity = AddressEntity::find()->where(["user_id"=>$userId,"id"=>$id,"del_flag"=>0])->one();
        if(!$entity) {
            throw new OaException(ErrorCode::ADDRESS_NOT_404);
        }
        return $entity;
    }

    public function updateDefault($userId){
         AddressEntity::updateAll(["is_default"=>0],["user_id"=>$userId,"del_flag"=>0]);
    }

    /**
     * @param ReqId $req
     * @return bool
     * @throws OaException
     */
    public function delAddress(ReqId $req) {
        $e = $this->findByIdAndUserId($req->getId(),$req->getUserId());
        $e->setDelFlag(1);
        $e->save();
        return true;
    }

    /**
     * @param ReqAddAddress $req
     * @return bool
     * @throws OaException
     */
    public function updateAddress(ReqAddAddress $req) {
        if($req->getIsDefault() == 1 ) {
            $this->updateDefault($req->getUserId());
        }

        $e = $this->findByIdAndUserId($req->getId(),$req->getUserId());
        $e->setProvince($req->getProvince());
        $e->setCity($req->getCity());
        $e->setDistrict($req->getDistrict());
        $e->setDetailAddress($req->getDetailAddress());
        $e->setUserId($req->getUserId());
        $e->setIsDefault($req->getIsDefault());
        $e->setReceiveName($req->getReceiveName());
        $e->setReceivePhone($req->getReceivePhone());
        $e->setUpdateTime(date("Y-m-d G:i:s"));
        $e->save();
        return true;
    }


    /**
     * @param ReqAddAddress $req
     * @return bool
     */
    public  function addAddress(ReqAddAddress $req){
        $time = date("Y-m-d G:i:s");

        if($req->getIsDefault() == 1 ) {
            $this->updateDefault($req->getUserId());
        }

        $e = new AddressEntity();
        $e->setProvince(strip_tags($req->getProvince()));
        $e->setCity(strip_tags($req->getCity()));
        $e->setDistrict(strip_tags($req->getDistrict()));
        $e->setDetailAddress(strip_tags($req->getDetailAddress()));
        $e->setUserId($req->getUserId());
        $e->setReceiveName(strip_tags($req->getReceiveName()));
        $e->setReceivePhone(strip_tags($req->getReceivePhone()));
        $e->setIsDefault($req->getIsDefault());
        $e->setCreateTime($time);
        $e->setUpdateTime($time);
        $e->setDelFlag(0);
        $e->save();


        return true;
    }

    /**
     * @param int $userId
     * @return RespPage
     */
    public function listPage($userId) {
        $data = AddressEntity::find()->where(["del_flag"=>0,"user_id"=>$userId])->orderBy("id desc");
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 100,'page'=>0]);
        /**@var $entities AddressEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];

        foreach ($entities as $entity) {
            $resp = new RespAddressDetail();
            $resp->setId($entity->getId());
            $resp->setReceiveName($entity->getReceiveName());
            $resp->setReceivePhone($entity->getReceivePhone());
            $resp->setProvince($entity->getProvince());
            $resp->setCity($entity->getCity());
            $resp->setDistrict($entity->getDistrict());
            $resp->setDetailAddress($entity->getDetailAddress());
            $resp->setIsDefault($entity->getIsDefault());
            array_push($list,$resp);
        }
        $resp = new RespPage();
        $resp->setTotal(intval($pages->totalCount));
        $resp->setPageSize($pages->getPageSize());
        $resp->setPageNo(1);
        $resp->setList($list);
        return $resp;
    }
}